/**
 * 
 */
package org.homeunix.thecave.plugins;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.swing.JOptionPane;
import javax.swing.JDialog;

import org.homeunix.thecave.buddi.plugin.api.BuddiExportPlugin;
import org.homeunix.thecave.buddi.plugin.api.exception.PluginException;
import org.homeunix.thecave.buddi.plugin.api.exception.PluginMessage;
import org.homeunix.thecave.buddi.plugin.api.model.ImmutableDocument;
import org.homeunix.thecave.buddi.plugin.api.model.ImmutableAccount;
import org.homeunix.thecave.buddi.plugin.api.model.ImmutableTransaction;
import org.homeunix.thecave.buddi.plugin.api.util.TextFormatter;
import org.homeunix.thecave.moss.swing.MossDocumentFrame;
import org.homeunix.thecave.moss.util.Version;

/**
 * Export plugin class realizes the BuddiExportPlugin interface. Implements
 * the exportData method to provide capability to export Buddi transacions in
 * comma separated value (CSV) format.
 * 
 * @author Santthosh
 *
 */
public class CSV_Export extends BuddiExportPlugin {
	
	private ExportPanel exportPanel;
	private JDialog exportDialog;
	private ImmutableDocument immutableDocument;
	private List<ImmutableAccount> accountsList;
	private List<ImmutableTransaction> transactionsList;
	/*
	 * Constructor
	 */
	public CSV_Export()
	{
             
	}	

	/* (non-Javadoc)
	 * Implementation of the abstract method declared in the super class. Called
	 * when the user selects the CSV Export menu item in the application. Sets
	 * up and invokes the Export Options dialog including registering the event
	 * handlers for the dialog's buttons.
	 * 
	 * @see org.homeunix.thecave.buddi.plugin.api.BuddiExportPlugin#exportData(org.homeunix.thecave.buddi.plugin.api.model.ImmutableDocument, org.homeunix.thecave.moss.swing.MossDocumentFrame, java.io.File)
	 */
	@Override
	public void exportData(ImmutableDocument arg0, MossDocumentFrame arg1,
			File arg2) throws PluginException, PluginMessage {		   
		   immutableDocument = arg0;
		   
		   /* Retrieve the accounts and transactions lists from Buddi */
		   accountsList = immutableDocument.getImmutableAccounts();
		   transactionsList = immutableDocument.getImmutableTransactions();		   		
		   
		   exportPanel = new ExportPanel();                       
	       
		   /* Empty the accounts combo */
		   if (accountsList.size() > 0)
		   {
			   exportPanel.selectAccount.removeAllItems();
		   }
		   /* Populate the accounts combo with available accounts */
		   for(int i=0;i<accountsList.size();i++)
		   {
			   ImmutableAccount account = accountsList.get(i);
			   exportPanel.selectAccount.addItem(account.getName());
		   }	
		   
		   /* Set up the event handler for the Export button */ 
	       exportPanel.export.addActionListener(new java.awt.event.ActionListener() {
	        	public void actionPerformed(java.awt.event.ActionEvent evt) {
	               exportActionPerformed(evt);
	        	}
	        });
	          
	       /* Set up the event handler for the Cancel button */
	       exportPanel.cancel.addActionListener(new java.awt.event.ActionListener() {
	        	public void actionPerformed(java.awt.event.ActionEvent evt) {
	                    cancelActionPerformed(evt);
	                }
	        });
	        
	       /* Load the Buddi icon to display in the task bar */
	       java.awt.Image image = new javax.swing.ImageIcon(ClassLoader.getSystemResource("img/BuddiFrameIcon.gif")).getImage();
	                     
	       /* Initialize and add the export dialog to the export panel */
	       exportDialog = new JDialog();
	       exportDialog.setModal(true);
	       exportDialog.setTitle("Export Buddi accounts to CSV file");                
	       exportDialog.setIconImage(image);
	       exportDialog.setLocationRelativeTo(null);        		        		
	       exportDialog.add(exportPanel);        
	       exportDialog.pack();
		   
		   exportDialog.setVisible(true);
	}
	
	/**
	 * Event handler for the Export button. Uses the options set in the
	 * Export Options dialog to export the selected transactions to a 
	 * user-specified file.
	 * 
	 * @param evt - unused
	 */
	public void exportActionPerformed(java.awt.event.ActionEvent evt)
	{
		File file;
		
		/* verify that the user has set an export filename */
		if(exportPanel.destinationPath.getText().trim()==null || exportPanel.destinationPath.getText().trim().isEmpty())
		{    	       	  
			javax.swing.JOptionPane.showMessageDialog(
					exportDialog, 
					"Please select a destination file for export", 
					"Missing file", 
					javax.swing.JOptionPane.ERROR_MESSAGE);
			return;
		}

		/* Create a new file to export to */
		file = new File(exportPanel.destinationPath.getText().trim());                  

		try 
		{
			/* Use the Decorator pattern to create file writer for the exported data. */
			FileWriter outFile = new FileWriter(file);
			PrintWriter out = new PrintWriter(outFile);											
			
			String csvRecord = 	"Date," + 
								"Number," +
								"Description," +
								"Amount," + 
								"BalanceFrom," +
								"BalanceTo," +
								"From," +
								"To," +
								"Memo";
			
			out.println(csvRecord);
			
			/* Iterate through the Buddi transactions creating an export record for each */
			for(int i=0;i<transactionsList.size();i++)
			{
				ImmutableTransaction transaction = transactionsList.get(i);
				
				/* Only get the transactions that are from the user selected account */
				if(exportPanel.selectedAccount.isSelected() &&
						!transaction.getFrom().getName().equals(exportPanel.selectAccount.getSelectedItem().toString()) &&
						!transaction.getTo().getName().equals(exportPanel.selectAccount.getSelectedItem().toString()))						
				{
					continue;				
				}
				/* create a delimited record string from the transaction */
				csvRecord = 	java.text.DateFormat.getDateInstance(java.text.DateFormat.SHORT).format(transaction.getDate()) + "," +
								transaction.getNumber()  + "," +
								transaction.getDescription()  + "," +
								(double)transaction.getAmount()/100  + "," +
								(double)transaction.getBalanceFrom()/100 + "," +
								(double)transaction.getBalanceTo()/100 + "," +
								transaction.getFrom().getName()  + "," +
								transaction.getTo().getName()  + "," +
								transaction.getMemo();
				
				/* Write the export record */
				out.println(csvRecord);
			}
			
			out.close();

			/* Let the user know that the export succeeded */
			javax.swing.JOptionPane.showMessageDialog(
					exportDialog, 
					"CSV Export to file " + file.getName() + " completed successfully.", 
					"Export Succeeded!", 
					javax.swing.JOptionPane.INFORMATION_MESSAGE);

		} catch (IOException e){
			e.printStackTrace();
			javax.swing.JOptionPane.showMessageDialog(
					exportDialog, 
					"Export failed! \nReason: "  + e.getMessage(), 
					"CSV Export Failure", 
					javax.swing.JOptionPane.ERROR_MESSAGE);
		}   
		finally
		{     
			exportDialog.dispose();
		}
	}
	
	/**
	 * Closes and cleans up the export dialog
	 * 
	 * @param evt - unused
	 */
	public void cancelActionPerformed(java.awt.event.ActionEvent evt)
	{
		exportDialog.dispose();
	}

	/* (non-Javadoc)
	 * Create the file menu item name for the CSV exporter
	 * @see org.homeunix.thecave.moss.plugin.MossPlugin#getName()
	 */
	@Override
	public String getName() {
		return TextFormatter.getTranslation("CSV Export");		
	}
	
	@Override
	public boolean isPromptForFile() {
		return false;
	}

	public Version getMaximumVersion() {
		return null;
	}

	public Version getMinimumVersion() {
		return null;
	}
	
}
